﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text; 
using Runda.CMS.Dal;
using System.Data;
using Runda.CMS.Common.Entity;
using Runda.CMS.Common.Utility;
using Runda.CMS.Common.Log;
using log4net;
using System.Transactions;

namespace Runda.CMS.Bll
{
    /// <summary>
    /// 系统管理业务逻辑
    /// </summary>
    public class SystemBll:BllBase
    {
        private ILog log = log4net.LogManager.GetLogger("myLogger");

        private string CacheName = "GetAllUser";
        public SystemBll()
        {
            _cacheName = "UserAllCache";
        }

        #region Role Bussiness
        /// <summary>
        /// 保存角色信息以及该角色的权限列表
        /// </summary>
        /// <param name="entity"></param>
        public void SaveRole(SysRoleEntity entity)
        {
            SysRoleDal RoldDal = new SysRoleDal();
            SysRoleFunctionRelationDal RoleFunDal = new SysRoleFunctionRelationDal();

            using (var tran = new System.Transactions.TransactionScope())
            {
                RoldDal.InsertOrUpdate(entity);

                if (entity.RoleFunctionRelateList != null)
                {
                    List<SqlDbParameter> parms = new List<SqlDbParameter>();
                    SqlDbParameter parm = new SqlDbParameter();
                    parm.ColumnName = "RoleID"; parm.ColumnType = DbType.Guid; parm.ParameterName = "@RoleID"; parm.ParameterValue = entity.RoleID; parm.QualificationType = SqlDbParameter.QualificationSymbol.Equal;
                    parms.Add(parm);
                    RoleFunDal.Delete<SysRoleFunctionRelationEntity>(parms);
                    foreach (SysRoleFunctionRelationEntity RoleFunEntity in entity.RoleFunctionRelateList)
                    {
                        RoleFunDal.Insert(RoleFunEntity);
                    }
                }
                tran.Complete();
                log.Info(new LogContent(LogType.info, "SystemBll",entity.CreatedBy.ToString() ,"", "保存角色"));
            }
        }

        #endregion

        #region Function Bussiness
        /// <summary>
        /// 根据角色构造功能点树
        /// </summary>
        /// <param name="RoleID"></param>
        /// <returns></returns>
        public DataTable BuildAllFunction(Guid RoleID)
        {
            SysFunctionDal dal = new SysFunctionDal();
            return dal.BuildAllFunction(RoleID);
        }

        /// <summary>
        /// 获取功能点树数据
        /// </summary>
        /// <param name="UserID"></param>
        /// <returns></returns>
        public List<SysFunctionEntity> LoadTreeFunctionEntitiesByUserID(Guid UserID)
        {
            SysFunctionDal dal = new SysFunctionDal();
            return dal.LoadTreeFunctionEntitiesByUserID(UserID);
        }
        #endregion

        #region User Bussiness
        /// <summary>
        /// 修改密码
        /// </summary>
        /// <param name="entity"></param>
        /// <param name="OldPassword">加密后的旧密码</param>
        /// <param name="NewPassword"></param>
        /// <returns></returns>
        public OperateResult ChangePassword(SysUserEntity entity,string OldPassword, string NewPassword)
        {
            OperateResult result = new OperateResult();
            //检查旧密码是否相同
            if (entity.Password != OldPassword)
            {
                result.ErrorCode = OperateStatus.ToViewError;
                result.ErrorMessage = "旧密码不正确!";
                return result;
            }
            SysUserDal dal = new SysUserDal();
            try
            {
                dal.UpdatePassword(entity.UserID, NewPassword);
                log.Info(new LogContent(LogType.info, "SystemBll", entity.CreatedBy.ToString(), "", "用户密码变更"));
            }
            catch(Exception ex)
            {
                result.ErrorCode = OperateStatus.ToViewError;
                result.ErrorMessage = "保存过程中发生错误!";
 
                log.Error(new LogContent(LogType.err, "SystemBll", entity.CreatedBy.ToString(), "", "改变用户密码异常"+ex.Message));
            }
            return result;
        }

        /// <summary>
        /// 检查用户是否具有某权限
        /// </summary>
        /// <param name="UserID">用户ID</param>
        /// <param name="CheckType">0: by URL,  1: by FunctionCode </param>
        /// <param name="CheckObject">Url or FunctionCode</param>
        /// <returns></returns>
        public bool CheckUserHasFuction(Guid UserID, int CheckType, string CheckObject)
        {
            SysFunctionDal FunDal = new SysFunctionDal();
            List<SysFunctionEntity> Funcs = FunDal.LoadUserHavedFunction(UserID);
            if (CheckType == 0)
            {
               return Funcs.Exists(delegate(SysFunctionEntity entity) { return entity.URL.ToLower() == CheckObject.ToLower(); });
            }
            else
            {
                return Funcs.Exists(delegate(SysFunctionEntity entity) { return entity.FuncID.ToLower() == CheckObject.ToLower(); });
            } 
        }

        /// <summary>
        /// 保存用户信息以及该用户的角色列表
        /// </summary>
        /// <param name="entity"></param>
        public void SaveUser(SysUserEntity entity)
        {
            SysUserDal UserDal = new SysUserDal();
            SysUserRoleRelationDal UserRoleDal = new SysUserRoleRelationDal();
            SysUserDepartmentDal UserDeptDal = new SysUserDepartmentDal();

            using (var tran = new System.Transactions.TransactionScope())
            {
                UserDal.InsertOrUpdate(entity);

                if (entity.UserRoleRelationList != null)
                {
                    //角色
                    List<SqlDbParameter> parms = new List<SqlDbParameter>();
                    SqlDbParameter parm = new SqlDbParameter();
                    parm.ColumnName = "UserID"; parm.ColumnType = DbType.Guid; parm.ParameterName = "@UserID"; parm.ParameterValue = entity.UserID; parm.QualificationType = SqlDbParameter.QualificationSymbol.Equal;
                    parms.Add(parm);
                    UserRoleDal.Delete<SysUserRoleRelationEntity>(parms);
                    foreach (SysUserRoleRelationEntity UserRoleEntity in entity.UserRoleRelationList)
                    {
                        UserRoleDal.Insert(UserRoleEntity);
                    }

                }

                if (entity.UserDepartmentList != null)
                {
                    //部门
                    List<SqlDbParameter>  parms = new List<SqlDbParameter>();
                    SqlDbParameter parm = new SqlDbParameter();
                    parm.ColumnName = "UserID"; parm.ColumnType = DbType.Guid; parm.ParameterName = "@UserID"; parm.ParameterValue = entity.UserID; parm.QualificationType = SqlDbParameter.QualificationSymbol.Equal;
                    parms.Add(parm);
                    UserRoleDal.Delete<SysUserDepartmentEntity>(parms);
                    foreach (SysUserDepartmentEntity UserDeptEntity in entity.UserDepartmentList)
                    {
                        UserDeptDal.Insert(UserDeptEntity);
                    }
                }

                if (entity.UserDepartmentDataRightList != null)
                {
                    //部门数据权限
                    List<SqlDbParameter> parms = new List<SqlDbParameter>();
                    SqlDbParameter parm = new SqlDbParameter();
                    parm.ColumnName = "UserID"; parm.ColumnType = DbType.Guid; parm.ParameterName = "@UserID"; parm.ParameterValue = entity.UserID; parm.QualificationType = SqlDbParameter.QualificationSymbol.Equal;
                    parms.Add(parm);
                    UserRoleDal.Delete<SysUserDepartmentDataRightEntity>(parms);
                    foreach (SysUserDepartmentDataRightEntity UserDeptEntity in entity.UserDepartmentDataRightList)
                    {
                        UserDeptDal.Insert(UserDeptEntity);
                    }
                }

                if (entity.UserProductCategoryList != null)
                {
                    //部门数据权限
                    List<SqlDbParameter> parms = new List<SqlDbParameter>();
                    SqlDbParameter parm = new SqlDbParameter();
                    parm.ColumnName = "UserID"; parm.ColumnType = DbType.Guid; parm.ParameterName = "@UserID"; parm.ParameterValue = entity.UserID; parm.QualificationType = SqlDbParameter.QualificationSymbol.Equal;
                    parms.Add(parm);
                    UserRoleDal.Delete<SysUserProductCategoryEntity>(parms);
                    foreach (SysUserProductCategoryEntity UserDeptEntity in entity.UserProductCategoryList)
                    {
                        UserDeptDal.Insert(UserDeptEntity);
                    }
                }


                tran.Complete();
                log.Info(new LogContent(LogType.info, "SystemBll", entity.CreatedBy.ToString(), "", "保存用户信息"));
            }
        }

        /// <summary>
        /// 根据用户构造部门树
        /// </summary>
        /// <param name="RoleID"></param>
        /// <returns></returns>
        public DataTable BuildAllDepartment(Guid UserID)
        {
            SysDepartmentDal dal = new SysDepartmentDal();
            return dal.BuildAllDepartment(UserID);
        }

        public DataTable BuildAllDepartmentByDataRight(Guid UserID)
        {
            SysDepartmentDal dal = new SysDepartmentDal();
            return dal.BuildAllDepartmentByDataRight(UserID);
        }

        public DataTable BuildAllProductCategory(Guid UserID)
        {
            SysDepartmentDal dal = new SysDepartmentDal();
            return dal.BuildAllProductCategory(UserID);
        }

        public DataTable BuildAllProductCategory()
        {
            SysDepartmentDal dal = new SysDepartmentDal();
            return dal.BuildAllProductCategory();
        }

        public List<SysDepartmentEntity> GetParentDepartment(Guid DepartmentID)
        {
            SysDepartmentDal dal = new SysDepartmentDal();
            return dal.GetParentDepartmentEntities(DepartmentID);
        }

        public List<SysDepartmentEntity> GetChildDepartment(Guid DepartmentID)
        {
            SysDepartmentDal dal = new SysDepartmentDal();
            return dal.GetChildDepartmentEntities(DepartmentID);
        }

        public List<SysUserEntity> GetAllUserFromCache()
        {

            if (base.ExistsCacheData(CacheName))
            {
                return GetCacheData(CacheName) as List<SysUserEntity>;
            }
            else
            {
                SysUserDal dal = new SysUserDal();
                List<SysUserEntity> list = dal.GetAll<SysUserEntity>(" and Deleted = 0"," order by UserName");

                AddCache(CacheName, list);

                return list;
            }

        }

        public List<SysUserEntity> GetAllUser()
        {

            SysUserDal dal = new SysUserDal();
            List<SysUserEntity> list = dal.GetAll<SysUserEntity>(" and Deleted = 0", " order by UserName");

            return list;

        }


        public SysUserEntity GetUserEntityFromCache(Guid UserID)
        {
            if (base.ExistsCacheData(CacheName))
            {
                List<SysUserEntity> list = null;
                list = GetCacheData(CacheName) as List<SysUserEntity>;

                return list.Find(delegate(SysUserEntity e) { return e.UserID == UserID; });
            }
            else
            {
                SysDictionaryDal dal = new SysDictionaryDal();
                List<SysUserEntity> list = dal.GetAll<SysUserEntity>(" and Deleted = 0");

                AddCache(CacheName, list);

                return list.Find(delegate(SysUserEntity e) { return e.UserID == UserID; });
            }
        }


        public DataTable GetUsersByDeptID(Guid DepartmentID)
        {
            SysUserDal dal = new SysUserDal();
            return dal.GetUsersByDeptID(DepartmentID);
        }

        public DataTable GetUsersByRole(int roleType)
        {
            SysUserDal dal = new SysUserDal();
            return dal.GetUsersByRole(roleType);
        }

        public void ReStartUser(string userID, string UpdatedBy)
        {
            string sql = "update cms_sys_user set Deleted = 0 where userid ='" + userID + "'";
            SysUserDal dal = new SysUserDal();

            try
            {
                dal.Executesql(sql);
                log.Info(new LogContent(LogType.info, "SystemBll", UpdatedBy, "", "重新启用用户"));
            }
            catch (Exception ex)
            {
                log.Error(new LogContent(LogType.err, "SystemBll", UpdatedBy, "", "重新启用用户异常" + ex.Message));
            }

        }

        public void ReSetPwd(string userID, string UpdatedBy)
        {
            SysUserDal dal = new SysUserDal();
            try
            {
                dal.UpdatePassword(new Guid(userID), System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile("123456", "MD5"));
                log.Info(new LogContent(LogType.info, "SystemBll", UpdatedBy, "", "重设用户密码"));
            }
            catch (Exception ex)
            {
                log.Error(new LogContent(LogType.err, "SystemBll", UpdatedBy, "", "重设用户密码异常" + ex.Message));
            }
        }
        
        #endregion

        #region Desktop Bussiness

        public DataTable getPriWebPart(Guid UserID)
        {
            DataTable dt = new DataTable();
            SysWebpartsDal dal = new SysWebpartsDal();
            return dal.getPrivateWebPart(UserID);
        }

        public DataTable getPublicWebPart()
        {
            DataTable dt = new DataTable();
            SysWebpartsDal dal = new SysWebpartsDal();
            return dal.getPublicWebPart();
        }

        public DataTable getPublicDesktopWebPart()
        {
            return new SysDesktopWebPartsDal().getPubliDesktopWebParts();
        }

        public DataTable getPrivateDesktopWebPart(Guid UserID)
        {
            return new SysDesktopWebPartsDal().getPrivateDesktopWebParts(UserID);
        }

        public void persistMyDeskTop(SysDesktopEntity desktopEntity)
        {

            using (System.Transactions.TransactionScope trans = new System.Transactions.TransactionScope())
            {
                this.Insert(desktopEntity);
                foreach (SysDesktopWebPartsEntity entity in desktopEntity.SysDesktopWebPartsEntityList)
                {
                    this.Insert(entity);
                }
                trans.Complete();
            }
            log.Info(new LogContent(LogType.info, "MyDesktopBll", desktopEntity.Owner.ToString(), "", "建立个人工作台"));
        }

        public void mergeMyDesktop(SysDesktopEntity desktopEntity)
        { 
            using (System.Transactions.TransactionScope trans = new System.Transactions.TransactionScope())
            {
                this.Update(desktopEntity);
                List<SqlDbParameter> parms = new List<SqlDbParameter>();
                SqlDbParameter parm = new SqlDbParameter();
                parm.ColumnName = "DesktopID";
                parm.ColumnType = DbType.Guid;
                parm.ParameterName = "@DesktopID";
                parm.ParameterValue = desktopEntity.DesktopID;
                parm.QualificationType = SqlDbParameter.QualificationSymbol.Equal;
                parms.Add(parm);
                this.Delete<SysDesktopWebPartsEntity>(parms);

                foreach (SysDesktopWebPartsEntity entity in desktopEntity.SysDesktopWebPartsEntityList)
                {
                    this.Insert(entity);
                }
                trans.Complete();
            }
            log.Info(new LogContent(LogType.info, "MyDesktopBll", desktopEntity.Owner.ToString(), "", "修改个人工作台"));
        }
        #endregion

        #region Notice Bussiness
        public void createMyNotice(CtrtMyNoticeEntity entity)
        {
            using (TransactionScope trans = new TransactionScope())
            {
                this.Insert(entity);
                foreach (CtrtMyNoticeUserEntity noticeUserEntity in entity.CtrtMyNoticeUserEntityList)
                {
                    this.Insert(noticeUserEntity);
                }
                trans.Complete();
            }
        }

        public DataTable QueryDuty(string whereClause, string OrderBy, int PageSize, int PageIndex, out int RecordCount)
        {
            SysDutyDal dal = new SysDutyDal();
            return dal.QueryDuty(whereClause, OrderBy, PageSize, PageIndex, out RecordCount);
        }

        public DataTable QueryDutyAll(string whereClause, string OrderBy, int PageSize, int PageIndex, out int RecordCount)
        {
            SysDutyDal dal = new SysDutyDal();
            return dal.QueryDutyAll(whereClause, OrderBy, PageSize, PageIndex, out RecordCount);
        }


        public void SaveNotice(CtrtMyNoticeEntity entity)
        {
            if (entity == null) return;

            using (System.Transactions.TransactionScope tran = new TransactionScope())
            {
                this.InsertOrUpdate(entity);

                if (entity.CtrtMyNoticeDepartmentEntityList != null && entity.CtrtMyNoticeDepartmentEntityList.Count > 0)
                {
                    this.Delete<CtrtMyNoticeDepartmentEntity>(" and NoticeID='"+entity.NoticeID+"'");
                    foreach (CtrtMyNoticeDepartmentEntity dept in entity.CtrtMyNoticeDepartmentEntityList)
                    {
                        this.Insert(dept);
                    }
                }
                tran.Complete();
            }
        }

        //判断是否休息日
        public int IsHoliday(string day)
        {
            string sqlSb = @"select count(*) from Cms_Sys_Dictionary where Type = 7 and code= '" + day + "'";


            int RecordCount = Convert.ToInt32(new CommonBll().getDataFromSQL(sqlSb).Rows[0][0]);
            return RecordCount;
        }
        #endregion


        #region Helper Methods
      
        #endregion
    }
}
